/**
 * 发送邮件类
 */

import * as nodemail from "nodemailer";
import { ConfigService } from "@nestjs/config";

export class EmailTool {
  // 创建服务
  private transporter = null;

  constructor(private configService: ConfigService) {
    // 创建一个服务
    this.transporter = nodemail.createTransport({
      host: this.configService.get("EMAIL").host,
      port: this.configService.get("EMAIL").port,
      secure: this.configService.get("EMAIL").secure,
      auth: {
        user: this.configService.get("EMAIL").user,
        pass: this.configService.get("EMAIL").pass
      }
    });
  }

  send({ email, subject, text, html, attachments = [] }: Send) {
    const options = {
      from: `${this.configService.get("EMAIL").alias}<${this.configService.get("EMAIL").user}>`,
      to: email,
      subject,
      text,
      html,
      attachments
    };

    return new Promise((resolve, reject) => {
      this.transporter.sendMail(options, (error, info) => {
        if (error) return reject(error);
        resolve(info);
      });
    });
  }
}

export interface Send {
  email: string;
  subject: string;
  text?: string;
  html?: string;
  attachments?: Array<Attachment>;
}

export interface Attachment {
  filename: string;
  path: string;
}
